package com.github.hwangrq.minicat.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author hwangrq
 * @date 2021/3/14 2:23
 * @description
 */
public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String classDicPath = StaticResourceUtil.class.getResource("/").getPath();
        return classDicPath + path.replaceAll("/", "");
    }

    /**
     * 读取静态资源文件输入流，通过输出流输出
     * @param in InputStream
     * @param out OutputStream
     */
    public static void outputStaticResource(InputStream in, OutputStream out) throws IOException {
        int resourceSize = 0;
        while (resourceSize == 0) {
            resourceSize = in.available();
        }
        // 输出 http 请求头
        out.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        // 读取内容输出
        long written  = 0; // 已经读取内容长度
        int byteSize = 1024; //计划每次缓存长度
        byte[] bytes = new byte[byteSize];
        while (written < byteSize) {
            // 说明剩余未读取的大小不足一个1024byteSize
            if (written + byteSize > resourceSize) {
                // 真实剩余文件的内容长度
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            in.read(bytes);
            out.write(bytes);

            out.flush();
            written+=byteSize;
        }

    }
}
